from collections import OrderedDict
from pprint import pprint

from django import http
from django.shortcuts import render
from django.views import View

from .models import Content, ContentCategory
from .utils import get_categories


class IndexView(View):
    def get(self, request):

        # 1.获取 商品分类数据
        categories = get_categories()

        # 2.获取广告数据
        contents = {}

        # 1. 获取所有的 广告分类 ContentCategory
        content_categories = ContentCategory.objects.all()

        # 2. 遍历广告分类
        for cat in content_categories:
            # 3. 根据分类 获取 对应 广告内容 Content==1:n
            contents[cat.key] = cat.content_set.filter(status=True).order_by('sequence')

        # 8.构建前端数据
        context = {
            'categories': categories,
            'contents': contents
        }
        pprint(contents)
        # 9.返回渲染的模板文件--- 数据 -- 自行渲染
        return render(request, 'index.html', context)
